var Admin = function() {
};

$.extend(Admin.prototype, {
	login : function(form) {
		form.find(".btn").button("loading");
		form.find(".label-danger").hide();
		$.post("/login/action?" + form.serialize(), function(data) {
			form.find(".btn").button("reset");
			if (data.code === 0) {
				form.find(".label-danger").html(data.msg).show();
				return;
			}
			window.location.href = "/admin";
		});
		return false;
	},
	
	initNav : function(wrap){
		var menu = [{id:1,parent:0,title:"Dashboard",href:"#"},
		            {id:2,parent:0,title:"Posts",href:"#"},
		            {id:3,parent:0,title:"Comments",href:"#"},
		            {id:4,parent:0,title:"Users",href:"#"},
		            {id:5,parent:0,title:"Tools",href:"#"},
		            {id:6,parent:0,title:"Settings",href:"#"},
		            {id:7,parent:2,title:"Add New",href:"#posts/add"},
		            {id:8,parent:2,title:"All Posts",href:"#posts"},
		            {id:9,parent:2,title:"Drafts",href:"#posts/drafts"},
		            {id:10,parent:4,title:"Add New",href:"#users/new"},
		            {id:11,parent:4,title:"All Users",href:"#users"},
		            {id:12,parent:4,title:"User Profile",href:"#users/info"},
		            {id:13,parent:6,title:"General",href:"#settings/general"}];
		var self = this,navWrap = $("<ul />").addClass("nav bs-sidenav");
		for(var i=0;i<menu.length;i++){
			if(menu[i].parent==0){
				var item = $("<li />"),olWrap = $("<ol />").addClass("nav"),flag=false;
				item.append("<a href="+menu[i].href+">"+menu[i].title+"</a>");
				for(var j=0;j<menu.length;j++){
					if(menu[j].parent == menu[i].id){
						flag = true;
						olWrap.append($("<li />").append("<a href="+menu[j].href+">"+menu[j].title+"</a>"));
					}
				}
				item.find("a").on("click",function(){
					$(this).parent().siblings().find("ol.nav").slideUp();
					$(this).parent().find("ol.nav").slideToggle();
				})
				item.append(flag==true?olWrap:"");
				navWrap.append(item);
			}
		}
		navWrap.find("li > a").on("click",function(){
			navWrap.find("li.active").removeClass("active");
			$(this).parent().addClass("active");
			self._getCon($(this).attr("href"));
		});
		wrap.append(navWrap);
	},
	
	_getCon : function(action){
		if(action=="#"){
			return;
		}
		var selector = ".col-lg-10",
			params = {},
			response,
			loading;
		
		$.ajax({
			url : "/admin"+action.replace("#","/"),
			type : "get",
			dataType: "html",
			data: params,
			beforeSend : function(){
				loading = $("#loading").fadeIn();
			}
		}).done(function( responseText ) {
			response = arguments;
			var respObj = jQuery("<div>").append( jQuery.parseHTML( responseText,true ) );
			jQuery("#content").html( selector ? respObj.find( selector ).children() : responseText );
		}).complete(function( jqXHR, status ) {
			loading.fadeOut();
		});
	}
});

$.admin = new Admin();
$.admin.initNav($("#nav"));